package com.xinpu.config;

import com.baomidou.mybatisplus.core.parser.ISqlParser;
import com.baomidou.mybatisplus.extension.plugins.PaginationInterceptor;
import com.baomidou.mybatisplus.extension.plugins.pagination.optimize.JsqlParserCountOptimize;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantHandler;
import com.baomidou.mybatisplus.extension.plugins.tenant.TenantSqlParser;
import com.xinpu.service.OwnService;
import com.xinpu.shiro.Loginer;
import net.sf.jsqlparser.expression.Expression;
import net.sf.jsqlparser.expression.StringValue;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;


@Configuration
public class MybatisPlusConfig {


    /**
     * 分页
     *
     * @return
     */
    @Bean
    public PaginationInterceptor paginationInterceptor() {
        PaginationInterceptor paginationInterceptor = new PaginationInterceptor();
        paginationInterceptor.setCountSqlParser(new JsqlParserCountOptimize(true));
        // 创建SQL解析器集合
        List<ISqlParser> sqlParserList = new ArrayList<>();

        // 创建租户SQL解析器
        TenantSqlParser tenantSqlParser = new TenantSqlParser();

        // 设置租户处理器
        tenantSqlParser.setTenantHandler(new TenantHandler() {

            @Override
            public Expression getTenantId(boolean select) {
                Loginer loginer = OwnService.getLoginer();
                return new StringValue(loginer.getTenantId());
            }

            @Override
            public String getTenantIdColumn() {
                // 对应数据库租户ID的列名
                return "tenant_id";
            }

            @Override
            public boolean doTableFilter(String tableName) {
                if (OwnService.getLoginer() == null) {
                    return true;
                }
                // 是否需要需要过滤某一张表
                List<String> tableNameList = Arrays.asList(
                        "t_company_wx_message_user",
                        "t_price",
                        "t_menus",
                        "t_order_buy",
                        "t_sales_photo",
                        "t_handover_log",
                        "t_handover_apply",
                        "t_apply",
                        "t_daily",
                        "t_sales_task_map",
                        "t_sales_thing",
                        "t_follow",
                        "t_user_tag_map",
                        "t_user_record"
                );
                if (tableNameList.contains(tableName)) {
                    return true;
                }
                return false;
            }
        });

        sqlParserList.add(tenantSqlParser);
        paginationInterceptor.setSqlParserList(sqlParserList);
        return paginationInterceptor;
    }


}

